﻿using App.Model;
using System.Reflection;
using System.Windows.Forms;

namespace App.UI
{
    internal class TabItem : TableLayoutPanel
    {
        private MainArea main;
        private Record[] records;
        private Tree leftTree;
        private Panel mainPanel;
        private CheckBox rightCheckBox;

        public TabItem(int index)
        {
            this.ColumnCount = 3;
            this.RowCount = 1;

            this.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 25.00F));
            this.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50.00F));
            this.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 25.00F));

            leftTree = new Tree()
            {
                Dock = DockStyle.Fill
            };
            TreeModel treeModel = Mock.GetTreeModel();
            leftTree.setModel(treeModel);
            leftTree.NodeStateChanged += NodeStateChanged;

            rightCheckBox = new CheckBox()
            {
                Dock = DockStyle.Fill
            };

            string label = Mock.GetTabs()[index];
            records = Mock.GetCheckboxData(label);
            rightCheckBox.setData(records);
            rightCheckBox.RecordItemCheck += OnRecordItemCheck;

            mainPanel = new Panel()
            {
                Dock = DockStyle.Fill
            };

            main = new MainArea();
          //  HslLineChart chart = new HslLineChart();
            mainPanel.Controls.Add(main);

            this.Controls.Add(leftTree, 0, 0);
            this.Controls.Add(mainPanel, 1, 0);
            this.Controls.Add(rightCheckBox, 2, 0);

            this.Dock = DockStyle.Fill;
        }

        private void NodeStateChanged(object sender, Tree.TreeNodeEvent e) 
        {
            SetLineSeries(e.Label, e.State);
        }

        private void OnRecordItemCheck(object sender, CheckBox.RecordEvent e) {
            if (main.Chart != null)
            {
                string label = records[e.Index].Label;
                SetLineSeries(label, e.State);
                main.Chart.UpdateAnnotations();
            }
        }

        private void SetLineSeries(string label, bool isRmove)
        {
            string[] names = Mock.GetNames(label);
            foreach (string name in names)
            {
                if (isRmove)
                {
                    main.Chart.RemoveLineSeries(name);
                }
                else
                {
                    int[] data = Mock.GetSeriesData();
                    main.Chart.AddLineSeries(name, data);
                }
                main.Chart.UpdateAnnotations();
            }
        }
    }
}
